﻿using AutoMapper;
using B.S.BaseData.Domain.Entities;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.Read.API.Command.MenuCommand;
using B.S.BaseData.Read.API.DTO;
using MediatR;

namespace B.S.BaseData.Read.API.CommandHandler.MenuHandler
{
    public class GetMenuHandler : IRequestHandler<GetMenuCommand, APIResult<List<CaseMenuDTO>>>
    {
        private readonly IBaseRepository<MenuManagement> _baseRepository;
        private readonly IMapper _mapper;

        public GetMenuHandler(IBaseRepository<MenuManagement> baseRepository, IMapper mapper)
        {
            _baseRepository = baseRepository;
            _mapper = mapper;
        }

        public async Task<APIResult<List<CaseMenuDTO>>> Handle(GetMenuCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<CaseMenuDTO>> result = new APIResult<List<CaseMenuDTO>>();
            result.Code = APIEnum.Success;
            result.Msg = "获取成功";
            result.Data = GetMenuTree(0);


            return await Task.FromResult(result);
            
        }

        public List<CaseMenuDTO> GetMenuTree(int id)
        {
            var ids = _baseRepository.GetAll().Where(p => p.ParentId == id);

            var dtos = _mapper.Map<List<CaseMenuDTO>>(ids);

            foreach (var d in dtos)
            {
                d.Children = GetMenuTree(d.MenuId);
            }

            return dtos;
        }
    }
}
